using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using JGSY.CMS.LowCode.Platform.Application.DTOs;
using JGSY.CMS.LowCode.Platform.Application.DTOs.Monitoring;
using JGSY.CMS.LowCode.Platform.Application.Interfaces;
using JGSY.CMS.LowCode.Platform.Domain.Entities;

namespace JGSY.CMS.LowCode.Platform.Controllers
{
    /// <summary>
    /// 租户监控管理API控制器
    /// </summary>
    [ApiController]
    [Route("api/tenant-monitoring")]
    [Authorize]
    public class TenantMonitoringController : ControllerBase
    {
        private readonly ITenantMonitoringService _monitoringService;
        private readonly ILogger<TenantMonitoringController> _logger;

        public TenantMonitoringController(
            ITenantMonitoringService monitoringService,
            ILogger<TenantMonitoringController> logger)
        {
            _monitoringService = monitoringService;
            _logger = logger;
        }

        #region 系统监控

        /// <summary>
        /// 获取系统指标
        /// </summary>
        [HttpGet("{tenantId}/system/metrics")]
        public async Task<IActionResult> GetSystemMetrics(Guid tenantId)
        {
            try
            {
                var result = await _monitoringService.GetSystemMetricsAsync(tenantId);
                return Ok(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取系统指标失败 for tenant {TenantId}", tenantId);
                return StatusCode(500, new { message = "获取系统指标失败", error = ex.Message });
            }
        }

        /// <summary>
        /// 获取系统指标历史数据
        /// </summary>
        [HttpGet("{tenantId}/system/metrics/history")]
        public async Task<IActionResult> GetSystemMetricsHistory(
            Guid tenantId, 
            [FromQuery] DateTime startTime, 
            [FromQuery] DateTime endTime)
        {
            try
            {
                var result = await _monitoringService.GetSystemMetricsHistoryAsync(tenantId, startTime, endTime);
                return Ok(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取系统指标历史数据失败 for tenant {TenantId}", tenantId);
                return StatusCode(500, new { message = "获取系统指标历史数据失败", error = ex.Message });
            }
        }

        /// <summary>
        /// 获取系统健康状态
        /// </summary>
        [HttpGet("{tenantId}/system/health")]
        public async Task<IActionResult> GetSystemHealth(Guid tenantId)
        {
            try
            {
                var result = await _monitoringService.GetSystemHealthAsync(tenantId);
                return Ok(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取系统健康状态失败 for tenant {TenantId}", tenantId);
                return StatusCode(500, new { message = "获取系统健康状态失败", error = ex.Message });
            }
        }

        #endregion

        #region 性能监控

        /// <summary>
        /// 获取性能指标
        /// </summary>
        [HttpGet("{tenantId}/performance/metrics")]
        public async Task<IActionResult> GetPerformanceMetrics(Guid tenantId)
        {
            try
            {
                var result = await _monitoringService.GetPerformanceMetricsAsync(tenantId);
                return Ok(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取性能指标失败 for tenant {TenantId}", tenantId);
                return StatusCode(500, new { message = "获取性能指标失败", error = ex.Message });
            }
        }

        /// <summary>
        /// 获取性能指标历史数据
        /// </summary>
        [HttpGet("{tenantId}/performance/metrics/history")]
        public async Task<IActionResult> GetPerformanceMetricsHistory(
            Guid tenantId, 
            [FromQuery] DateTime startTime, 
            [FromQuery] DateTime endTime)
        {
            try
            {
                var result = await _monitoringService.GetPerformanceMetricsHistoryAsync(tenantId, startTime, endTime);
                return Ok(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取性能指标历史数据失败 for tenant {TenantId}", tenantId);
                return StatusCode(500, new { message = "获取性能指标历史数据失败", error = ex.Message });
            }
        }

        /// <summary>
        /// 生成性能报告
        /// </summary>
        [HttpGet("{tenantId}/performance/report")]
        public async Task<IActionResult> GeneratePerformanceReport(
            Guid tenantId, 
            [FromQuery] DateTime startTime, 
            [FromQuery] DateTime endTime)
        {
            try
            {
                var result = await _monitoringService.GeneratePerformanceReportAsync(tenantId, startTime, endTime);
                return Ok(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "生成性能报告失败 for tenant {TenantId}", tenantId);
                return StatusCode(500, new { message = "生成性能报告失败", error = ex.Message });
            }
        }

        #endregion

        #region 用户活动监控

        /// <summary>
        /// 获取用户活动数据
        /// </summary>
        [HttpGet("{tenantId}/user-activity")]
        public async Task<IActionResult> GetUserActivity(Guid tenantId)
        {
            try
            {
                var result = await _monitoringService.GetUserActivityAsync(tenantId);
                return Ok(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取用户活动数据失败 for tenant {TenantId}", tenantId);
                return StatusCode(500, new { message = "获取用户活动数据失败", error = ex.Message });
            }
        }

        /// <summary>
        /// 获取用户活动历史数据
        /// </summary>
        [HttpGet("{tenantId}/user-activity/history")]
        public async Task<IActionResult> GetUserActivityHistory(
            Guid tenantId, 
            [FromQuery] DateTime startTime, 
            [FromQuery] DateTime endTime)
        {
            try
            {
                var result = await _monitoringService.GetUserActivityHistoryAsync(tenantId, startTime, endTime);
                return Ok(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取用户活动历史数据失败 for tenant {TenantId}", tenantId);
                return StatusCode(500, new { message = "获取用户活动历史数据失败", error = ex.Message });
            }
        }

        /// <summary>
        /// 获取用户活动摘要
        /// </summary>
        [HttpGet("{tenantId}/user-activity/summary")]
        public async Task<IActionResult> GetUserActivitySummary(
            Guid tenantId, 
            [FromQuery] DateTime date)
        {
            try
            {
                var result = await _monitoringService.GetUserActivitySummaryAsync(tenantId, date);
                return Ok(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取用户活动摘要失败 for tenant {TenantId}", tenantId);
                return StatusCode(500, new { message = "获取用户活动摘要失败", error = ex.Message });
            }
        }

        #endregion

        #region 错误监控

        /// <summary>
        /// 获取错误日志
        /// </summary>
        [HttpGet("{tenantId}/errors")]
        public async Task<IActionResult> GetErrorLogs(
            Guid tenantId, 
            [FromQuery] int pageIndex = 0, 
            [FromQuery] int pageSize = 50)
        {
            try
            {
                var result = await _monitoringService.GetErrorLogsAsync(tenantId, pageIndex, pageSize);
                return Ok(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取错误日志失败 for tenant {TenantId}", tenantId);
                return StatusCode(500, new { message = "获取错误日志失败", error = ex.Message });
            }
        }

        /// <summary>
        /// 获取特定错误详情
        /// </summary>
        [HttpGet("errors/{errorId}")]
        public async Task<IActionResult> GetErrorLog(Guid errorId)
        {
            try
            {
                var result = await _monitoringService.GetErrorLogAsync(errorId);
                return Ok(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取错误详情失败 for error {ErrorId}", errorId);
                return StatusCode(500, new { message = "获取错误详情失败", error = ex.Message });
            }
        }

        /// <summary>
        /// 获取错误统计
        /// </summary>
        [HttpGet("{tenantId}/errors/statistics")]
        public async Task<IActionResult> GetErrorStatistics(
            Guid tenantId, 
            [FromQuery] DateTime startTime, 
            [FromQuery] DateTime endTime)
        {
            try
            {
                var result = await _monitoringService.GetErrorStatisticsAsync(tenantId, startTime, endTime);
                return Ok(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取错误统计失败 for tenant {TenantId}", tenantId);
                return StatusCode(500, new { message = "获取错误统计失败", error = ex.Message });
            }
        }

        /// <summary>
        /// 标记错误为已解决
        /// </summary>
        [HttpPut("errors/{errorId}/resolve")]
        public async Task<IActionResult> MarkErrorAsResolved(
            Guid errorId, 
            [FromBody] string resolution)
        {
            try
            {
                await _monitoringService.MarkErrorAsResolvedAsync(errorId, resolution);
                return Ok(new { message = "错误已标记为解决" });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "标记错误为已解决失败 for error {ErrorId}", errorId);
                return StatusCode(500, new { message = "标记错误为已解决失败", error = ex.Message });
            }
        }

        #endregion

        #region 警报管理

        /// <summary>
        /// 获取警报列表
        /// </summary>
        [HttpGet("{tenantId}/alerts")]
        public async Task<IActionResult> GetAlerts(Guid tenantId)
        {
            try
            {
                var result = await _monitoringService.GetAlertsAsync(tenantId);
                return Ok(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取警报列表失败 for tenant {TenantId}", tenantId);
                return StatusCode(500, new { message = "获取警报列表失败", error = ex.Message });
            }
        }

        /// <summary>
        /// 创建警报
        /// </summary>
        [HttpPost("{tenantId}/alerts")]
        public async Task<IActionResult> CreateAlert(Guid tenantId, [FromBody] object request)
        {
            try
            {
                var result = await _monitoringService.CreateAlertAsync(tenantId, request);
                return CreatedAtAction(nameof(GetAlerts), new { tenantId }, result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "创建警报失败 for tenant {TenantId}", tenantId);
                return StatusCode(500, new { message = "创建警报失败", error = ex.Message });
            }
        }

        /// <summary>
        /// 更新警报
        /// </summary>
        [HttpPut("alerts/{alertId}")]
        public async Task<IActionResult> UpdateAlert(Guid alertId, [FromBody] object request)
        {
            try
            {
                var result = await _monitoringService.UpdateAlertAsync(alertId, request);
                return Ok(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "更新警报失败 for alert {AlertId}", alertId);
                return StatusCode(500, new { message = "更新警报失败", error = ex.Message });
            }
        }

        /// <summary>
        /// 删除警报
        /// </summary>
        [HttpDelete("alerts/{alertId}")]
        public async Task<IActionResult> DeleteAlert(Guid alertId)
        {
            try
            {
                await _monitoringService.DeleteAlertAsync(alertId);
                return NoContent();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "删除警报失败 for alert {AlertId}", alertId);
                return StatusCode(500, new { message = "删除警报失败", error = ex.Message });
            }
        }

        /// <summary>
        /// 获取触发的警报
        /// </summary>
        [HttpGet("{tenantId}/alerts/triggered")]
        public async Task<IActionResult> GetTriggeredAlerts(Guid tenantId)
        {
            try
            {
                var result = await _monitoringService.GetTriggeredAlertsAsync(tenantId);
                return Ok(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取触发警报失败 for tenant {TenantId}", tenantId);
                return StatusCode(500, new { message = "获取触发警报失败", error = ex.Message });
            }
        }

        #endregion

        #region 实时监控

        /// <summary>
        /// 获取实时指标
        /// </summary>
        [HttpGet("{tenantId}/realtime/metrics")]
        public async Task<IActionResult> GetRealTimeMetrics(Guid tenantId)
        {
            try
            {
                var result = await _monitoringService.GetRealTimeMetricsAsync(tenantId);
                return Ok(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取实时指标失败 for tenant {TenantId}", tenantId);
                return StatusCode(500, new { message = "获取实时指标失败", error = ex.Message });
            }
        }

        /// <summary>
        /// 启动实时监控
        /// </summary>
        [HttpPost("{tenantId}/realtime/start")]
        public async Task<IActionResult> StartRealTimeMonitoring(Guid tenantId)
        {
            try
            {
                await _monitoringService.StartRealTimeMonitoringAsync(tenantId);
                return Ok(new { message = "实时监控已启动" });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "启动实时监控失败 for tenant {TenantId}", tenantId);
                return StatusCode(500, new { message = "启动实时监控失败", error = ex.Message });
            }
        }

        /// <summary>
        /// 停止实时监控
        /// </summary>
        [HttpPost("{tenantId}/realtime/stop")]
        public async Task<IActionResult> StopRealTimeMonitoring(Guid tenantId)
        {
            try
            {
                await _monitoringService.StopRealTimeMonitoringAsync(tenantId);
                return Ok(new { message = "实时监控已停止" });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "停止实时监控失败 for tenant {TenantId}", tenantId);
                return StatusCode(500, new { message = "停止实时监控失败", error = ex.Message });
            }
        }

        #endregion

        #region 报告生成

        /// <summary>
        /// 生成监控报告
        /// </summary>
        [HttpGet("{tenantId}/reports/monitoring")]
        public async Task<IActionResult> GenerateMonitoringReport(
            Guid tenantId, 
            [FromQuery] DateTime startTime, 
            [FromQuery] DateTime endTime, 
            [FromQuery] string format = "pdf")
        {
            try
            {
                var result = await _monitoringService.GenerateMonitoringReportAsync(tenantId, startTime, endTime, format);
                return File(result, GetContentType(format), $"monitoring-report-{tenantId}-{DateTime.UtcNow:yyyyMMddHHmmss}.{format}");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "生成监控报告失败 for tenant {TenantId}", tenantId);
                return StatusCode(500, new { message = "生成监控报告失败", error = ex.Message });
            }
        }

        /// <summary>
        /// 生成仪表板
        /// </summary>
        [HttpGet("{tenantId}/dashboard")]
        public async Task<IActionResult> GenerateDashboard(
            Guid tenantId, 
            [FromQuery] string format = "pdf")
        {
            try
            {
                var result = await _monitoringService.GenerateDashboardAsync(tenantId, format);
                return File(result, GetContentType(format), $"dashboard-{tenantId}-{DateTime.UtcNow:yyyyMMddHHmmss}.{format}");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "生成仪表板失败 for tenant {TenantId}", tenantId);
                return StatusCode(500, new { message = "生成仪表板失败", error = ex.Message });
            }
        }

        #endregion

        #region 阈值管理

        /// <summary>
        /// 获取阈值列表
        /// </summary>
        [HttpGet("{tenantId}/thresholds")]
        public async Task<IActionResult> GetThresholds(Guid tenantId)
        {
            try
            {
                var result = await _monitoringService.GetThresholdsAsync(tenantId);
                return Ok(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取阈值列表失败 for tenant {TenantId}", tenantId);
                return StatusCode(500, new { message = "获取阈值列表失败", error = ex.Message });
            }
        }

        /// <summary>
        /// 创建阈值
        /// </summary>
        [HttpPost("{tenantId}/thresholds")]
        public async Task<IActionResult> CreateThreshold(Guid tenantId, [FromBody] object request)
        {
            try
            {
                var result = await _monitoringService.CreateThresholdAsync(tenantId, request);
                return CreatedAtAction(nameof(GetThresholds), new { tenantId }, result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "创建阈值失败 for tenant {TenantId}", tenantId);
                return StatusCode(500, new { message = "创建阈值失败", error = ex.Message });
            }
        }

        /// <summary>
        /// 更新阈值
        /// </summary>
        [HttpPut("thresholds/{thresholdId}")]
        public async Task<IActionResult> UpdateThreshold(Guid thresholdId, [FromBody] object request)
        {
            try
            {
                var result = await _monitoringService.UpdateThresholdAsync(thresholdId, request);
                return Ok(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "更新阈值失败 for threshold {ThresholdId}", thresholdId);
                return StatusCode(500, new { message = "更新阈值失败", error = ex.Message });
            }
        }

        /// <summary>
        /// 删除阈值
        /// </summary>
        [HttpDelete("thresholds/{thresholdId}")]
        public async Task<IActionResult> DeleteThreshold(Guid thresholdId)
        {
            try
            {
                await _monitoringService.DeleteThresholdAsync(thresholdId);
                return NoContent();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "删除阈值失败 for threshold {ThresholdId}", thresholdId);
                return StatusCode(500, new { message = "删除阈值失败", error = ex.Message });
            }
        }

        #endregion

        #region 趋势分析

        /// <summary>
        /// 分析趋势
        /// </summary>
        [HttpGet("{tenantId}/trends/analyze")]
        public async Task<IActionResult> AnalyzeTrends(
            Guid tenantId, 
            [FromQuery] string metricType, 
            [FromQuery] DateTime startTime, 
            [FromQuery] DateTime endTime)
        {
            try
            {
                var result = await _monitoringService.AnalyzeTrendsAsync(tenantId, metricType, startTime, endTime);
                return Ok(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "分析趋势失败 for tenant {TenantId}, metric {MetricType}", tenantId, metricType);
                return StatusCode(500, new { message = "分析趋势失败", error = ex.Message });
            }
        }

        /// <summary>
        /// 预测趋势
        /// </summary>
        [HttpGet("{tenantId}/trends/predict")]
        public async Task<IActionResult> PredictTrends(
            Guid tenantId, 
            [FromQuery] string metricType, 
            [FromQuery] int days = 30)
        {
            try
            {
                var result = await _monitoringService.PredictTrendsAsync(tenantId, metricType, days);
                return Ok(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "预测趋势失败 for tenant {TenantId}, metric {MetricType}", tenantId, metricType);
                return StatusCode(500, new { message = "预测趋势失败", error = ex.Message });
            }
        }

        #endregion

        #region 私有方法

        /// <summary>
        /// 根据格式获取Content-Type
        /// </summary>
        private static string GetContentType(string format)
        {
            return format.ToLower() switch
            {
                "pdf" => "application/pdf",
                "excel" => "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
                "csv" => "text/csv",
                "json" => "application/json",
                _ => "application/octet-stream"
            };
        }

        #endregion
    }
}
